<?php
/**
 * Purchase.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-22
 * Time: 11:23
 */

namespace App\Http\Controllers\Api\Inventory;


use App\Exceptions\RunException;
use App\Http\Controllers\Base;
use App\Tables;
class Purchase extends Base
{
    public function getList()
    {
        $firstDate = $this->request->get('firstDate');
        $lastDate = $this->request->get('lastDate');

        $table = Tables\Purchase::query();
        if(!empty($firstDate) and !empty($lastDate)) {
            $table->whereBetween('add_time', [strtotime($firstDate), strtotime($lastDate) + 86400]);
        } else {
            $firstDate = date('Ym01');
            $lastDate  = date('Ym01',strtotime('+1 month'));
            $table->whereBetween('add_time', [strtotime($firstDate), strtotime($lastDate)]);
        }
        $list = $table->orderBy('id', 'desc')->get();
        $r = [];
        foreach($list as $v) {
            $dt = [];
            foreach($v->details as $d) {
                $dt[] = [
                    'name' => $d['name'],
                    'desc' => $d['desc'],
                    'unit' => $d['unit'],
                    'price' => $d['price'],
                    'number' => $d['number'],
                ];
            }
            $r[] = [
                'id' => $v['id'],
                'name' => $v['name'],
                'contact' => $v['contact'],
                'beginDate' => $v['begin_date'],
                'completeDate' => $v['complete_date'],
                'price' => $v['price'],
                'remark' => $v['remark'],
                'editable' => !empty($v['complete_date']) ? 0 : 1,
                'detail' => $dt,
            ];
        }
        return $this->responseSuccess(['header' => ['total' => count($r)], 'list' => $r]);
    }

    public function add()
    {
        $name = $this->request->post('name');
        $contact = $this->request->post('contact');
        $beginDate = $this->request->post('beginDate');
        $completeDate = $this->request->post('completeDate');
        $price = (double) $this->request->post('price');
        $remark = $this->request->post('remark');
        $detail = (array) $this->request->post('detail', []);

        if(empty($name)) { return $this->responseFail('名称不能为空');}
        if(empty($beginDate)) { return $this->responseFail('进货日期不能为空');}
        if(empty($detail)) { return $this->responseFail('进货明细不能为空');}

        \DB::beginTransaction();

        try {
            $addTime = time();
            $cid = 0;
            $beginDate =  date('Y-m-d', strtotime($beginDate)) ;
            if(!empty($completeDate)) {
                $completeDate = date('Y-m-d', strtotime($completeDate));
                if($price <= 0) { throw new RunException('增加失败(1)');}
                $cid = (int) Tables\CashFlow::insertGetId([
                    'change' => -$price,
                    'desc'   => '从供应商'.$name.'进货花费'.$price.'元',
                    'type'   => Tables\CashFlow::TYPE_Outcome_Stock,
                    'add_time' => $addTime
                ]);
                if($cid <= 0) { throw  new RunException('增加失败(2)');}
            } else {
                $completeDate = null;
            }

            $pid = (int) Tables\Purchase::insertGetId([
                'name' => $name,
                'contact' => $contact,
                'begin_date' => $beginDate,
                'complete_date' => $completeDate,
                'price' => $price,
                'remark' => $remark,
                'cid' => $cid,
                'add_time' => $addTime
            ]);
            if($pid <= 0) { throw new RunException('增加失败(3)'); }

            $insertData = [];
            foreach($detail as $d) {
                if(empty($d['name']) or empty($d['price']) or empty($d['number'])) {
                    throw new RunException('数据不完整!');
                }
                $insertData[] = [
                    'pid' => $pid,
                    'name' => $d['name'],
                    'desc' => $d['desc']??'',
                    'unit' => $d['unit']??'',
                    'number' => $d['number'],
                    'price' => $d['price'],
                    'add_time' => $addTime
                ];
            }

            $ok = (bool) Tables\PurchaseDetail::insert($insertData);
            if(!$ok) { throw new RunException('增加失败(4)');}
            \DB::commit();
        } catch(RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage().'数据库错误');
        }
        return $this->responseSuccess();
    }

    public function update()
    {
        $pid = (int) $this->request->post('id', 0);
        $name = $this->request->post('name');
        $contact = $this->request->post('contact');
        $beginDate = $this->request->post('beginDate');
        $completeDate = $this->request->post('completeDate');
        $price = (double) $this->request->post('price');
        $remark = $this->request->post('remark');
        $detail = (array) $this->request->post('detail', []);
        if($pid<=0) {return $this->responseFail('无信息');}
        if(empty($name)) { return $this->responseFail('名称不能为空');}
        if(empty($beginDate)) { return $this->responseFail('进货日期不能为空');}
        if(empty($detail)) { return $this->responseFail('进货明细不能为空');}

        $pData = Tables\Purchase::find($pid);
        if(empty($pData)) { return $this->responseFail('没有找到信息');}
        if(!empty($pData['complete_date'])) { return $this->responseFail('此单已完成无法修改！');}

        \DB::beginTransaction();

        try {
            $addTime = time();
            $cid = 0;
            $beginDate =  date('Y-m-d', strtotime($beginDate)) ;
            if(!empty($completeDate)) {
                $completeDate = date('Y-m-d', strtotime($completeDate));
                if($price <= 0) { throw new RunException('修改失败(1)');}
                $cid = (int) Tables\CashFlow::insertGetId([
                    'change' => -$price,
                    'desc'   => '从供应商'.$name.'进货花费'.$price.'元',
                    'type'   => Tables\CashFlow::TYPE_Outcome_Stock,
                    'add_time' => $addTime
                ]);
                if($cid <= 0) { throw  new RunException('修改失败(2)');}
            } else {
                $completeDate = null;
            }

            $ok = (bool) Tables\Purchase::where('id', $pid)->update([
                'name' => $name,
                'contact' => $contact,
                'begin_date' => $beginDate,
                'complete_date' => $completeDate,
                'price' => $price,
                'remark' => $remark,
                'cid' => $cid,
                'update_time' => date('Y-m-d H:i:s')
            ]);
            if($ok <= 0) { throw new RunException('修改失败(3)'); }

            $insertData = [];
            foreach($detail as $d) {
                if(empty($d['name']) or empty($d['price']) or empty($d['number'])) {
                    throw new RunException('数据不完整!');
                }
                $insertData[] = [
                    'pid' => $pid,
                    'name' => $d['name'],
                    'desc' => $d['desc']??'',
                    'unit' => $d['unit']??'',
                    'number' => $d['number'],
                    'price' => $d['price'],
                    'add_time' => $addTime
                ];
            }
            $ok = (bool) Tables\PurchaseDetail::where('pid', $pid)->delete();
            if(!$ok) { throw new RunException('修改失败(4)');}
            $ok = (bool) Tables\PurchaseDetail::insert($insertData);
            if(!$ok) { throw new RunException('修改失败(5)');}
            \DB::commit();
        } catch(RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }

    public function del()
    {
        $id = (int) $this->request->post('id', 0);
        if($id <= 0) { return $this->responseFail('无信息');}
        $find = Tables\Purchase::find($id);
        if(empty($find)) { return $this->responseFail('查询不到信息！');}
        if(!empty($find['complete_date'])) { return $this->responseFail('订单已完成，无法删除'); }
        \DB::beginTransaction();
        try {
            foreach($find->details as $detail) {
                if(!(bool) $detail->delete()) {
                    throw new RunException('删除失败(1)');
                }
            }
            if(!(bool) $find->delete()) {
                throw new RunException('删除失败(2)');
            }
            \DB::commit();
        } catch(RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }
}